﻿using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Kugar.Core.BaseStruct;
using Kugar.Web.Wechat.Entities;
using Senparc.NeuChar;
using Senparc.NeuChar.Context;
using Senparc.NeuChar.Entities;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.Entities.Request;
using Senparc.Weixin.MP.MessageContexts;
using Senparc.Weixin.MP.MessageHandlers;

namespace Kugar.Web.Wechat.MP
{
    public class WeiXinMessageHandler : MessageHandler<DefaultMpMessageContext>
    {
        private IWechatMP _service = null;

        public WeiXinMessageHandler(IWechatMP service, Stream inputStream, PostModel postModel, int maxRecordCount = 0)
            : base(inputStream, postModel, maxRecordCount)
        {
            /*
            base.UsingEcryptMessage = false;
            base.UsingCompatibilityModelEcryptMessage = false;
            */
            _service = service;

            base.UsingEncryptMessage = false;
            base.UsingCompatibilityModelEncryptMessage = false;

            GlobalMessageContext.ExpireMinutes = 3;
            //这里设置仅用于测试，实际开发可以在外部更全局的地方设置，
            //比如MessageHandler<MessageContext>.GlobalWeixinContext.ExpireMinutes = 3。
            //GlobalWeixinContext.ExpireMinutes = 3;
        }

        public override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            var resp = await _service.ExecuteRequestMsg(
                convertTo(
                    (RequestMessageBase) RequestMessage)); // WebBLL.WeiXin.OnMessageReceiveOnce(convertTo((RequestMessageBase) RequestMessage));

            if (resp == null)
            {
                ResponseMessage = null;
                //return null;
            }
            else
            {
                ResponseMessage = convertTo(resp.ReturnData);
            }
        }


        //public override IResponseMessageBase OnEventRequest(IRequestMessageEventBase requestMessage)
        //{
        //    var str = WebBLL.WeiXin.OnMessageReceiveOnce(requestMessage.ToString());

        //    if (string.IsNullOrWhiteSpace(str))
        //    {
        //        return null;
        //    }

        //    return ResponseMessageFactory.GetResponseEntity(str);
        //}

        public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage)
        {
            return null;
        }

        private WechatRequestBase convertTo(RequestMessageBase msg)
        {
            switch (msg.MsgType)
            {
                case RequestMsgType.Text:
                    return (WechatRequestText) msg;

                case RequestMsgType.Image:
                    return (WechatRequestImage) msg;

                case RequestMsgType.Event:
                {
                    var eventMsg = (RequestMessageEventBase) msg;
                    switch (eventMsg.Event)
                    {
                        case Event.LOCATION:
                            return (WechatRequestEvent_Location) msg;
                        case Event.subscribe:
                            return (WechatRequestEvent_Subscribe) msg;
                        case Event.unsubscribe:
                            return (WechatRequestEvent_UnSubscribe) msg;
                        case Event.CLICK:
                            return (WechatRequestEvent_Click) msg;
                        case Event.scan:
                            return (WechatRequestEvent_Scan) msg;
                        case Event.scancode_push:
                        case Event.scancode_waitmsg:
                            return (WechatRequestEvent_ScancodePush)
                                (Senparc.Weixin.MP.Entities.RequestMessageEvent_Scancode_Push) msg;
                        case Event.VIEW:
                            return (WechatRequestEvent_View) msg;
                        case Event.location_select:
                            return (WechatRequesEvent_LocationSelect) msg;
                    }

                    break;
                }
            }

            return null;
        }

        private ResponseMessageBase convertTo(WechatResponseBase msg)
        {
            if (msg == null)
            {
                return null;
            }


            var wechat = WechatApi.Default.MP.GetWechatItemByAppID(msg.AppID);

            ResponseMessageBase resp = null;

            if (msg is WechatResponseText text)
            {
                ResponseMessageText text2 = new ResponseMessageText();
                text2.Content = text.Content;
                resp = text2;
            }
            else if (msg is WechatResponseImage image)
            {
                string str = image.Media_ID;
                if (string.IsNullOrWhiteSpace(str))
                {
                    ResultReturn<string> return2 =
                        WechatApi.Default.MP.UpdateImageMediaAsync(wechat.appID, image.ImagePath).Result;
                    if (return2.IsSuccess)
                    {
                        str = return2.ReturnData;
                    }
                }

                if (string.IsNullOrWhiteSpace(str))
                {
                    return null;
                }

                ResponseMessageImage image2 = new ResponseMessageImage();

                Image image3 = new Image {MediaId = str};

                image2.Image = image3;

                resp = image2;
            }
            else if (msg is WechatResponseNews news)
            {
                if (news.ArticleCount <= 0)
                {
                    return null;
                }

                var news2 = new ResponseMessageNews();

                news2.Articles = news.Articles.Select(item => new Article()
                {
                    Description = item.Description,
                    PicUrl = item.PicUrl,
                    Title = item.Title,
                    Url = item.Url
                }).ToList();

                news2.ArticleCount = news.ArticleCount;

                resp = news2;
            }

            if (resp != null)
            {
                resp.CreateTime = DateTime.Now;
                resp.FromUserName = wechat.wechatID;
                resp.ToUserName = msg.ToUserOpenID;
            }

            return resp;
        }
    }

}